<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\CardLevel;
use app\common\model\Goods;
use app\common\model\GoodsList;
use app\common\model\GoodsLock;
use app\common\model\ItemCard;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\OrderListSend;
use app\common\model\OrderSale;
use app\common\model\ProductOrder;
use app\common\model\ProductOrderList;
use app\common\model\ProfitPay;
use app\common\model\ProfitRank;
use app\common\model\ClimbUser;
use app\common\model\ClimbRank;
use app\common\model\ProfitScore;
use app\common\model\Shang;
use app\common\model\User;
use app\common\model\UserLevelCoupon;
use app\common\model\UserRecharge;
use app\common\model\Ads;
use think\facade\Db;
use think\facade\Log;
use app\common\model\CouponReceive as CouponReceiveModel;
use Payment\Config;
use Payment\Client\Notify as PayNotify;
use Payment\Common\PayException;
use app\common\server\PaymentNotify;

/**
 * Class Notify 同步处理
 * @package app\index\controller
 */
class Notify extends Base
{
    static $shang_prize_id = [10, 33]; #抽奖赏品id
    static $shang_give_first_id = 1; #赠送(FIRST赏)赏品id
    static $shang_give_arr = [2, 3, 4]; #赠送(LAST赏 最终赏 全局赏)赏品id
    static $shang_give_w_id = 4; #赠送(全局赏)赏品id
    static $shang_give_quan_id = 5; #赠送(拳王赏)赏品id
    static $secretKey = null;

    public function initialize()
    {
        $secret_key = getConfig('weixinpay')['keys'];
        static::$secretKey = $secret_key; //秘钥
    }

    public function ceshi()
    {
        $order['goods_id'] = 18;
        $order['num'] = 1;
        $order['order_type'] = 3;
        //        dd(11);
        $this->quan_prize_notice($order);
    }

    /**
     * 特殊奖品开奖 拳王赏
     * @param $order 订单信息
     */
    protected function quan_prize_notice($order)
    {
        $res = [];
        $goods_id = $order['goods_id'];
        $num = $order['num'];
        $order_type = $order['order_type'];
        #盒子
        $goods_info = Goods::field('prize_num,stock')->where(['id' => $goods_id])->find();
        #特殊奖品存在where('goods_id', '=', $goods_id)
        $special_prize = GoodsList::where('goods_id', '=', $goods_id)
            ->where('num', '=', $num)
            ->where('surplus_stock', '>', 0)
            ->where('shang_id', '=', self::$shang_give_quan_id)
            ->order('prize_num desc')
            ->select();
        // dd($special_prize);
        $user_ids = [];
        foreach ($special_prize as $value) {
            $surplus_give_stock = $value ? $value['surplus_stock'] : 0;
            if ($value && $surplus_give_stock > 0) {

                #符合条件的订单
                $quan_prize_num = $value['prize_num'];
                // dd($quan_prize_num);
                // var_dump($quan_prize_num);
                $prize_num_data = OrderList::field('id,user_id,count(`id`) as all_num')
                    ->where('goods_id', '=', $goods_id)
                    ->where('num', '=', $num)
                    ->where('order_type', '=', $order_type)
                    ->where('shang_id', '=', self::$shang_give_w_id) //4
                    ->having('all_num', '>=', $quan_prize_num)
                    ->group('user_id')
                    ->select()->toArray();

                $prize_num_data_arr = [];
                foreach ($prize_num_data as $val) {
                    if ($val['all_num'] >= $quan_prize_num && !in_array($val['user_id'], $user_ids)) {
                        $prize_num_data_arr[] = $val;
                    }
                }
                // dd($prize_num_data_arr);
                if ($prize_num_data_arr) {
                    // dd($prize_num_data);
                    #多个随机
                    shuffle($prize_num_data_arr);

                    $quan_prize_info = $prize_num_data_arr[0];

                    $user_id = $quan_prize_info['user_id'];
                    $user_ids[] = $quan_prize_info['user_id'];

                    $order_goods = [
                        'order_id' => 0,
                        'user_id' => $user_id,
                        'status' => 0, #0未操作 1选择兑换 2选择发货
                        'goods_id' => $goods_id,
                        'num' => $num,
                        'shang_id' => $value['shang_id'],
                        'goodslist_id' => $value['id'],
                        'goodslist_title' => $value['title'],
                        'goodslist_imgurl' => $value['imgurl'],
                        'goodslist_price' => $value['price'],
                        'goodslist_money' => $value['money'],
                        'goodslist_type' => $value['goods_type'],
                        'goodslist_sale_time' => $value['sale_time'],
                        'addtime' => time(),
                        'prize_code' => $value['prize_code'],
                        'order_type' => $order_type,
                        'order_list_id' => 0,
                    ];
                    // var_dump($order_goods);
                    #新增奖品列表
                    $res[] = OrderList::insert($order_goods);

                    #减少库存
                    $res[] = GoodsList::field('surplus_stock')
                        ->where(['id' => $value['id']])
                        ->dec('surplus_stock')
                        ->update();
                    //  var_dump($res);
                }
            }
        }
        #赏品
        $goods_list_zd = GoodsList::where(['goods_id' => $goods_id])
            ->where(['num' => 1])
            ->select()->toArray();
        if ($goods_list_zd) {
            #循环数据
            $save_sports_data = [];
            $start_num = $goods_info['stock'] + 1;
            for ($i = $start_num; $i <= $start_num; $i++) {
                foreach ($goods_list_zd as $k => $v) {
                    unset($v['id']);
                    unset($v['num']);
                    $v['num'] = $i;
                    $v['surplus_stock'] = $v['stock'];
                    $save_sports_data[] = $v;
                }
            }
            #添加赏品
            $res[] = GoodsList::insertAll($save_sports_data);
            #增加库存
            $res[] = Goods::where(['id' => $goods_id])->inc('stock', 1)->update();
        }
        return $res;
    }
    /**
     *
     * 获取支付结果通知数据
     * return array
     */
    public function order_notify()
    {
        #获取通知的数据
        $xml = file_get_contents("php://input");


        if (empty($xml)) {
            return false;
        }
        #转成数组
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        writelog('notify', $data);
        $sign = $data['sign'];
        unset($data['sign']);
        $newSign = $this->MakeSign($data);
        #验证签名
        if ($sign == $newSign) {
            //如果成功返回了
            if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
                $user = User::where('openid', $data['openid'])->find();
                try {
                    Db::name('wxpay_log')->insert([
                        'order_no' => $data['out_trade_no'],
                        'content' => json_encode($data),
                        'type' => 1,
                        'user_id' => $user['id'],
                        'addtime' => time(),
                    ]);
                } catch (\Throwable $e) {
                    $this->CallbackSuccess();
                }
                $out_trade_no = $data['out_trade_no']; //订单号
                $table = $data['attach']; #表名


                // $out_trade_no = 'MH_202411305198565106752';
                // $table = 'order_climb';
                if ($table == 'user_recharge') { #余额充值
                    $orderInfo = UserRecharge::where('order_num', '=', $out_trade_no)
                        ->where(['status' => 1])
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 1) {
                        $user_id = $orderInfo['user_id'];
                        $money = $orderInfo['money'];
                        Db::startTrans();
                        #修改订单状态
                        $res[] = UserRecharge::field('status,pay_time')
                            ->where(['id' => $orderInfo['id']])->update([
                                'status' => 2,
                                'pay_time' => time(),
                            ]);
                        $res[] = User::changeMoney($user_id, $money, 2, '在线充值');
                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $money,
                            'content' => '微信支付',
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);

                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                } elseif ($table == 'order_yfs' || $table == 'order_lts') { #抽赏一番赏 擂台赏
                    $orderInfo = Order::where('order_num', '=', $out_trade_no)
                        ->where('status', '=', 0)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 0) {
                        $user_id = $orderInfo['user_id'];
                        $price = $orderInfo['price'];
                        Db::startTrans();
                        try {
                            #开盒子
                            $res[] = $this->drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id'], $orderInfo['num']);

                            $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                            #广告收益回调
                            if (!empty($orderInfo['click_id']) && !empty($orderInfo['ad_id'])) {
                                $order_ad_num = Order::where('user_id', '=', $user_id)->where('status', '=', 1)->where('ad_id', '>', 0)->where('click_id', '>', 0)->where('price', '>', 0)->count();
                                if ($order_ad_num <= 1) {
                                    $this->ad_notify($orderInfo['ad_id'], $orderInfo['click_id']);
                                }
                            }
                        } catch (\Throwable $e) {
                            Db::rollback();
                            #卡单了
                            Order::field('kd_is')->where(['id' => $orderInfo['id']])
                                ->update(['kd_is' => 1]);
                            #通知微信
                            $this->CallbackSuccess();
                        }

                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $price,
                            'content' => '购买盒子' . $orderInfo['goods_title'],
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);
                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                } elseif ($table == 'order_wxs') { #抽赏无限赏
                    $orderInfo = Order::where('order_num', '=', $out_trade_no)
                        ->where('status', '=', 0)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 0) {
                        $user_id = $orderInfo['user_id'];
                        $price = $orderInfo['price'];
                        Db::startTrans();
                        $res[] = $this->infinite_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id']);
                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $price,
                            'content' => '购买盒子' . $orderInfo['goods_title'],
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);

                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                        #广告收益回调
                        if (!empty($orderInfo['click_id']) && !empty($orderInfo['ad_id'])) {
                            $order_ad_num = Order::where('user_id', '=', $user_id)->where('status', '=', 1)->where('ad_id', '>', 0)->where('click_id', '>', 0)->where('price', '>', 0)->count();
                            if ($order_ad_num <= 1) {
                                $this->ad_notify($orderInfo['ad_id'], $orderInfo['click_id']);
                            }
                        }
                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                } elseif ($table == 'order_ckj') { #抽赏抽卡机
                    $orderInfo = Order::where('order_num', '=', $out_trade_no)
                        ->where('status', '=', 0)
                        ->where('order_type', '=', 4)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 0) {
                        $user_id = $orderInfo['user_id'];
                        $price = $orderInfo['price'];
                        Db::startTrans();
                        $res[] = $this->cardextractor_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id']);
                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $price,
                            'content' => '购买盒子' . $orderInfo['goods_title'],
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);
                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                } elseif ($table == 'order_list_send') { #背包发货
                    $orderInfo = OrderListSend::where('send_num', '=', $out_trade_no)
                        ->where('status', '=', 0)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 0) {
                        $user_id = $orderInfo['user_id'];
                        $freight = $orderInfo['freight'];
                        Db::startTrans();
                        $res[] = $this->reward_order_handle($user_id, $orderInfo['id']);
                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $freight,
                            'content' => '背包发货',
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);

                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                } elseif ($table == 'order_js') { #集市购买
                    $orderInfo = Db::name('market_order')->where('order_num', '=', $out_trade_no)
                        ->where('status', '=', 1)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 1) {
                        $user_id = $orderInfo['user_id'];
                        $total_price = $orderInfo['total_price'];
                        Db::startTrans();
                        $res[] = $this->update_js_order($orderInfo['id']);
                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $total_price,
                            'content' => '集市购买',
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);

                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                            Db::name('market_order')->where('id', $orderInfo['id'])->update(['status' => 3, 'update_time' => time()]);
                        }
                    }
                } elseif ($table == 'order_climb') {  #爬塔
                    $orderInfo = Order::where('order_num', '=', $out_trade_no)
                        ->where('status', '=', 0)
                        ->find();
                    #这个订单存在状态对
                    if ($orderInfo && $orderInfo['status'] == 0) {
                        $user_id = $orderInfo['user_id'];
                        $price = $orderInfo['price'];
                        Db::startTrans();


                        try {

                            $res[] = $this->pata_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id'], $orderInfo['num']);
                        } catch (\Throwable $e) {
                            Db::rollback();
                            Log::error($e->getMessage());
                            file_put_contents('./climb.txt', json_encode($e->getMessage()));
                            #卡单了
                            Order::field('kd_is')->where(['id' => $orderInfo['id']])->update(['kd_is' => 1]);
                            $this->CallbackSuccess();
                        }

                        #记录微信支付
                        $res[] = ProfitPay::insert([
                            'user_id' => $user_id,
                            'order_num' => $out_trade_no,
                            'change_money' => $price,
                            'content' => '购买爬塔盒子' . $orderInfo['goods_title'],
                            'pay_type' => 1, #1微信 2支付宝
                            'addtime' => time(),
                        ]);

                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                        if (resCheck($res)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                            Order::field('kd_is')->where(['id' => $orderInfo['id']])->update(['kd_is' => 1]);
                            $this->CallbackSuccess();
                        }
                    }
                } elseif ($table == 'product_order') {   //商城购买
                    return $this->update_product_order($out_trade_no);
                }
            }
        }
        $this->CallbackSuccess();
    }
    /**
     *
     * 获取支付结果通知数据
     * return array
     */
    public function order_notify_ali()
    {
        #获取通知的数据
        $xml = file_get_contents("php://input");
        if (empty($xml)) {
            return false;
        }
        parse_str(strval($xml), $data);
        writelog('notify', $data);
        #转成数组
        if ($data['trade_status'] == 'TRADE_SUCCESS') {
            $out_trade_no = $data['out_trade_no']; //订单号
            $arr = explode(',', $data['body']);
            $table = $arr[0]; #表名
            //如果成功返回了
            $user = User::where('openid', $arr[1])->find();
            try {
                Db::name('wxpay_log')->insert([
                    'order_no' => $data['out_trade_no'],
                    'content' => json_encode($data),
                    'type' => 2,
                    'user_id' => $user['id'],
                    'addtime' => time(),
                ]);
            } catch (\Throwable $e) {
                $this->CallbackSuccess();
            }
            if ($table == 'user_recharge') { #余额充值
                $orderInfo = UserRecharge::where('order_num', '=', $out_trade_no)
                    ->where(['status' => 1])
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 1) {
                    $user_id = $orderInfo['user_id'];
                    $money = $orderInfo['money'];
                    Db::startTrans();
                    #修改订单状态
                    $res[] = UserRecharge::field('status,pay_time')
                        ->where(['id' => $orderInfo['id']])->update([
                            'status' => 2,
                            'pay_time' => time(),
                        ]);
                    $res[] = User::changeMoney($user_id, $money, 2, '在线充值');
                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $money,
                        'content' => '微信支付',
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);

                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                }
            } elseif ($table == 'order_yfs' || $table == 'order_lts') { #抽赏一番赏 擂台赏
                $orderInfo = Order::where('order_num', '=', $out_trade_no)
                    ->where('status', '=', 0)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 0) {
                    $user_id = $orderInfo['user_id'];
                    $price = $orderInfo['price'];
                    Db::startTrans();
                    try {
                        #开盒子
                        $res[] = $this->drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id'], $orderInfo['num'], 2);

                        $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                        #广告收益回调
                        if (!empty($orderInfo['click_id']) && !empty($orderInfo['ad_id'])) {
                            $order_ad_num = Order::where('user_id', '=', $user_id)->where('status', '=', 1)->where('ad_id', '>', 0)->where('click_id', '>', 0)->where('price', '>', 0)->count();
                            if ($order_ad_num <= 1) {
                                $this->ad_notify($orderInfo['ad_id'], $orderInfo['click_id']);
                            }
                        }
                    } catch (\Throwable $e) {
                        Db::rollback();
                        #卡单了
                        Order::field('kd_is')->where(['id' => $orderInfo['id']])
                            ->update(['kd_is' => 1]);
                        #通知微信
                        $this->CallbackSuccess();
                    }

                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $price,
                        'content' => '购买盒子' . $orderInfo['goods_title'],
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);
                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                }
            } elseif ($table == 'order_wxs') { #抽赏无限赏
                $orderInfo = Order::where('order_num', '=', $out_trade_no)
                    ->where('status', '=', 0)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 0) {
                    $user_id = $orderInfo['user_id'];
                    $price = $orderInfo['price'];
                    Db::startTrans();
                    $res[] = $this->infinite_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id'], 2);
                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $price,
                        'content' => '购买盒子' . $orderInfo['goods_title'],
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);

                    $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                    #广告收益回调
                    if (!empty($orderInfo['click_id']) && !empty($orderInfo['ad_id'])) {
                        $order_ad_num = Order::where('user_id', '=', $user_id)->where('status', '=', 1)->where('ad_id', '>', 0)->where('click_id', '>', 0)->where('price', '>', 0)->count();
                        if ($order_ad_num <= 1) {
                            $this->ad_notify($orderInfo['ad_id'], $orderInfo['click_id']);
                        }
                    }
                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                }
            } elseif ($table == 'order_ckj') { #抽赏抽卡机
                $orderInfo = Order::where('order_num', '=', $out_trade_no)
                    ->where('status', '=', 0)
                    ->where('order_type', '=', 4)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 0) {
                    $user_id = $orderInfo['user_id'];
                    $price = $orderInfo['price'];
                    Db::startTrans();
                    $res[] = $this->cardextractor_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id']);
                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $price,
                        'content' => '购买盒子' . $orderInfo['goods_title'],
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);
                    $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                }
            } elseif ($table == 'order_list_send') { #背包发货
                $orderInfo = OrderListSend::where('send_num', '=', $out_trade_no)
                    ->where('status', '=', 0)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 0) {
                    $user_id = $orderInfo['user_id'];
                    $freight = $orderInfo['freight'];
                    Db::startTrans();
                    $res[] = $this->reward_order_handle($user_id, $orderInfo['id']);
                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $freight,
                        'content' => '背包发货',
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);

                    $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                }
            } elseif ($table == 'order_js') { #集市购买
                $orderInfo = Db::name('market_order')->where('order_num', '=', $out_trade_no)
                    ->where('status', '=', 1)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 1) {
                    $user_id = $orderInfo['user_id'];
                    $total_price = $orderInfo['total_price'];
                    Db::startTrans();
                    $res[] = $this->update_js_order($orderInfo['id']);
                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $total_price,
                        'content' => '集市购买',
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);

                    $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);

                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                        Db::name('market_order')->where('id', $orderInfo['id'])->update(['status' => 3, 'update_time' => time()]);
                    }
                }
            } elseif ($table == 'order_climb') {  #爬塔
                $orderInfo = Order::where('order_num', '=', $out_trade_no)
                    ->where('status', '=', 0)
                    ->find();
                #这个订单存在状态对
                if ($orderInfo && $orderInfo['status'] == 0) {
                    $user_id = $orderInfo['user_id'];
                    $price = $orderInfo['price'];
                    Db::startTrans();


                    try {

                        $res[] = $this->pata_drawprize_notice($user_id, $orderInfo['id'], $orderInfo['goods_id'], $orderInfo['num'], 2);
                    } catch (\Throwable $e) {
                        Db::rollback();
                        Log::error($e->getMessage());
                        file_put_contents('./climb.txt', json_encode($e->getMessage()));
                        #卡单了
                        Order::field('kd_is')->where(['id' => $orderInfo['id']])->update(['kd_is' => 1]);
                        $this->CallbackSuccess();
                    }

                    #记录微信支付
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $price,
                        'content' => '购买爬塔盒子' . $orderInfo['goods_title'],
                        'pay_type' => 2, #1微信 2支付宝
                        'addtime' => time(),
                    ]);

                    $this->wx_gf_fahuo($user_id, $orderInfo['order_num']);
                    if (resCheck($res)) {
                        Db::commit();
                    } else {
                        Db::rollback();
                        Order::field('kd_is')->where(['id' => $orderInfo['id']])->update(['kd_is' => 1]);
                        $this->CallbackSuccess();
                    }
                }
            } elseif ($table == 'product_order') {   //商城购买
                return $this->update_product_order($out_trade_no, 2);
            }
        }
        $this->CallbackSuccess();
    }

    /*
   广告推广
   */
    public function ad_notify($ads_id, $click_id)
    {
        $tencent_ad = Ads::where('id', $ads_id)->find();
        if (!empty($tencent_ad)) {
            $result = tencent_ad_attribution($click_id, 1, $tencent_ad['account_id'], $tencent_ad['access_token'], $tencent_ad['user_action_set_id']);
            dump($result);
        }
    }

    /**
     * 生成签名
     * @return 签名
     */
    public function MakeSign($params)
    {
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . static::$secretKey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
    public function ToUrlParams($params)
    {
        $string = '';
        if (!empty($params)) {
            $array = array();
            foreach ($params as $key => $value) {
                $array[] = $key . '=' . $value;
            }
            $string = implode("&", $array);
        }
        return $string;
    }

    /**
     * 接收通知成功后应答输出XML数据
     * @param string $xml
     */
    public function CallbackSuccess()
    {
        $html = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        die($html);
    }

    /**
     * 一番抽赏开始抽赏======================================================
     * @param int $user_id 会员id
     * @param int $order_id 订单ID
     * @param int $goods_id 盒子id
     * @param int $num 盒子箱号
     */
    public function drawprize_notice($user_id = 0, $order_id = 0, $goods_id = 0, $num = 0, $pay_type = 1)
    {

        $res = [];
        $order = Order::where(['id' => $order_id])
            ->where(['user_id' => $user_id])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => $num])
            ->where(['status' => 0])
            ->where('order_type', 'in', [1, 3, 5, 6])
            ->find();

        if ($order) {
            #套库存=============================
            //            $all_stock = GoodsList::field('stock')->where('goods_id', '=', $goods_id)->where('num', '=', $num)
            //                ->where('shang_id', 'between', self::$shang_prize_id)->sum('stock');
            //            $redis = new \Redis();
            //            $redis->connect('127.0.0.1', 6379);
            //            $redis_key = 'kpw_' . $goods_id . '_' . $num;
            //            for ($r = 1; $r <= $order['prize_num']; $r++) {
            //                $redis->lPush($redis_key, 1);
            //            }
            //            $redis_len = $redis->lLen($redis_key);
            //            if ($redis_len >= $all_stock) {
            //                for ($l = 1; $l <= $order['prize_num']; $l++) {
            //                    $redis->rPop($redis_key);
            //                }
            //                #卡单了
            //                $kd_is = Order::field('kd_is')
            //                    ->where(['id' => $order['id']])
            //                    ->update([
            //                        'kd_is' => 1
            //                    ]);
            //                return $kd_is;
            //            }
            #套库存=============================


            #改变状态
            $res[] = Order::field('status,pay_time')
                ->where(['id' => $order['id']])
                ->update([
                    'status' => 1,
                    'pay_time' => time(),
                ]);

            #记录微信支付
            $res[] = ProfitRank::insert([
                'user_id' => $user_id,
                'order_num' => $order['order_num'],
                'change_money' => $order['order_total'],
                'content' => '购买盒子' . $order['goods_title'],
                'pay_type' => $pay_type, #1微信 2支付宝
                'addtime' => time(),
            ]);
            #扣余额
            if ($order['use_money'] > 0) {
                $res[] = User::changeMoney($order['user_id'], -$order['use_money'], 3, '购买盒子' . $order['goods_title']);
            }
            #扣潮币
            if ($order['use_integral'] > 0) {
                $res[] = User::changeIntegral($order['user_id'], -$order['use_integral'], 2, '购买盒子' . $order['goods_title']);
            }
            #扣积分
            if ($order['use_score'] > 0) {
                $res[] = User::changeScore($order['user_id'], -$order['use_score'], 2, '购买盒子' . $order['goods_title']);
            }
            #判断一下优惠券
            if (!empty($order['coupon_id'])) {
                $coupon = CouponReceiveModel::where(['id' => $order['coupon_id'], 'status' => 0])->update(['status' => 1]);
            }
            #判断是否发积分 发券
            $res[] = User::is_integral_coupon($order);
            #判断是否发积分

            #分销奖励
            $res[] = User::distribution($order);
            #分销奖励

            #普通奖品==========================================================
            $res[] = $this->ordinary_prize_notice($order);
            #普通奖品==========================================================

            # 赠送欧气
            $ouqi_num = floor($order['order_total'] / 10);
            if ($ouqi_num > 0) {
                $tt = User::changeOuQi($user_id, $ouqi_num, 2, '消费赠送');
                User::ou_qi_level_up($user_id, $ouqi_num, 2);
                $res = array_merge($res, $tt);
            }
            # 赠送积分  比例 1:100
            $score_num = round(($order['order_total'] / 100), 2);
            User::changeScore($user_id, $score_num, 2, '消费赠送');


            #特殊奖品**********************************************************
            #普通奖品余量信息
            $goodslist = GoodsList::field('sum(`stock`) as stock, sum(`surplus_stock`) as surplus_stock')
                ->where('goods_id', '=', $goods_id)
                ->where('num', '=', $num)
                ->where('shang_id', 'between', self::$shang_prize_id)
                ->find();
            // var_dump($goodslist['surplus_stock']);
            #普通赏销量数量
            $sale_count = $goodslist['stock'] - $goodslist['surplus_stock'];
            #普通奖品一半
            $first_count = floor($goodslist['stock'] / 2);
            #FIRST
            if ($order['order_type'] != 3 && $sale_count >= $first_count) {
                $res[] = $this->special_first_notice($order, $first_count);
            }
            #LAST赏 全局赏 拳王赏
            if ($goodslist['surplus_stock'] <= 0) {
                // var_dump($goodslist['surplus_stock']);

                $res[] = $this->special_prize_notice($order, $first_count);
                // var_dump($res);
                #擂台赏
                if ($order['order_type'] == 3) { //3擂台赏
                    $res[] = $this->quan_prize_notice($order);
                }
                //冲锋
                $res[] = $this->chong_prize($order);

                #增加盒子库存
                $goods = Goods::field('id,stock,sale_stock')
                    ->where(['id' => $goods_id])
                    ->find();
                $save_update = [];
                $goods_sale_stock = $goods['sale_stock'] + 1;
                if ($goods_sale_stock >= $goods['stock']) {
                    // $save_update['status'] = 3;
                }
                $save_update['sale_stock'] = $goods_sale_stock;
                $res[] = Goods::field('id,status,sale_stock')
                    ->where(['id' => $goods_id])
                    ->update($save_update);
            }
            #特殊奖品**********************************************************
        } else {
            $res[] = 0;
        }
        return $res;
    }

    /**
     * 普通奖品开奖
     * @param $order 订单信息
     */
    protected function ordinary_prize_notice($order)
    {
        $user_id = $order['user_id'];
        $order_id = $order['id'];
        $goods_id = $order['goods_id'];
        $num = $order['num'];
        $order_type = $order['order_type'];
        #抽奖数量
        $prize_num = $order['prize_num'];
        #普通奖品信息
        $ordinary_prize = GoodsList::where('goods_id', '=', $goods_id)
            ->where('num', '=', $num)
            ->where('shang_id', 'between', self::$shang_prize_id)
            ->order('sort desc,shang_id asc')
            ->select()->toArray();
        if (!$ordinary_prize) {
            $res[] = 0;
            return $res;
        }
        #抽了多少抽
        $stock = array_sum(array_column($ordinary_prize, 'stock'));
        $surplus_stock = array_sum(array_column($ordinary_prize, 'surplus_stock'));
        $reward_num_count = $stock - $surplus_stock;
        #普通奖暂存信息
        $ordinary_prize_all = [];
        #其他
        $ordinary_prize_other = [];
        foreach ($ordinary_prize as $k => $v) {
            #剩余
            $surplus_prize = $v['surplus_stock'];
            for ($i = 1; $i <= $surplus_prize; $i++) {
                if ($v['reward_num'] > 0) {
                    if ($reward_num_count >= $v['reward_num']) {
                        #全部延迟出赏普通奖品
                        $ordinary_prize_other[] = $v;
                    }
                } else {
                    #全部未延迟出赏普通奖品
                    $ordinary_prize_other[] = $v;
                }
                #全部普通奖品
                $ordinary_prize_all[] = $v;
            }
        }
        if ($prize_num > count($ordinary_prize_other)) {
            #全部商品
            $end_ordinary_prize = $ordinary_prize_all;
        } else {
            #延迟出赏
            $end_ordinary_prize = $ordinary_prize_other;
        }
        shuffle($end_ordinary_prize);
        shuffle($end_ordinary_prize);

        $luck_no = OrderList::field('id')
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', $num)
            ->where('order_type', '=', $order_type)
            ->order('id desc')
            ->value('luck_no');
        // echo $luck_no; die;
        $luck_no++;

        #入库奖品
        $save_order_goods = [];
        #开普通奖品
        for ($i = 0; $i < $prize_num; $i++) {
            $ordinary_prize_info = $end_ordinary_prize[$i];
            $save_order_goods[] = [
                'order_id' => $order_id,
                'user_id' => $user_id,
                'status' => 0, #0未操作 1选择兑换 2选择发货
                'goods_id' => $goods_id,
                'num' => $num,
                'shang_id' => $ordinary_prize_info['shang_id'],
                'goodslist_id' => $ordinary_prize_info['id'],
                'goodslist_title' => $ordinary_prize_info['title'],
                'goodslist_imgurl' => $ordinary_prize_info['imgurl'],
                'goodslist_price' => $ordinary_prize_info['price'],
                'goodslist_money' => $ordinary_prize_info['money'],
                'goodslist_type' => $ordinary_prize_info['goods_type'],
                'goodslist_sale_time' => $ordinary_prize_info['sale_time'],
                'addtime' => time(),
                'luck_no' => $luck_no,
                'prize_code' => $ordinary_prize_info['prize_code'],
                'order_type' => $order_type,
            ];
            $luck_no++;
            #减少库存
            $res[] = GoodsList::field('surplus_stock')
                ->where(['id' => $ordinary_prize_info['id']])
                ->dec('surplus_stock')
                ->update();
        }
        if ($save_order_goods) {
            #新增奖品列表
            $res[] = OrderList::insertAll($save_order_goods);
        }
        return $res;
    }

    /**
     * 特殊奖品开奖 FIRST
     * @param $order 订单信息
     * @param $first_count
     */
    protected function special_first_notice($order, $first_count)
    {
        $res = [];
        $goods_id = $order['goods_id'];
        $num = $order['num'];
        $order_type = $order['order_type'];
        #特殊奖品存在
        $special_prize = GoodsList::where('goods_id', '=', $goods_id)
            ->where('num', '=', $num)
            ->where('surplus_stock', '>', 0)
            ->where('shang_id', '=', self::$shang_give_first_id)
            ->find();
        #剩余数量
        $surplus_give_stock = $special_prize ? $special_prize['surplus_stock'] : 0;
        if ($special_prize && $surplus_give_stock > 0) {
            #所有奖品信息
            $all_order_list = OrderList::where('goods_id', '=', $goods_id)
                ->where('num', '=', $num)
                ->where('order_type', '=', $order_type)
                ->where('shang_id', 'between', self::$shang_prize_id)
                ->order('id asc')
                ->limit((int) $first_count)
                ->select()->toArray();
            shuffle($all_order_list);
            shuffle($all_order_list);
            $prize_info = $all_order_list[0];
            $user_id = $prize_info['user_id'];
            #特殊赏中奖订单id
            $order_list_id = $prize_info['id'];
            #中奖奖项
            $order_goods = [
                'order_id' => 0,
                'user_id' => $user_id,
                'status' => 0, #0未操作 1选择兑换 2选择发货
                'goods_id' => $goods_id,
                'num' => $num,
                'shang_id' => $special_prize['shang_id'],
                'goodslist_id' => $special_prize['id'],
                'goodslist_title' => $special_prize['title'],
                'goodslist_imgurl' => $special_prize['imgurl'],
                'goodslist_price' => $special_prize['price'],
                'goodslist_money' => $special_prize['money'],
                'goodslist_type' => $special_prize['goods_type'],
                'goodslist_sale_time' => $special_prize['sale_time'],
                'addtime' => time(),
                'prize_code' => $special_prize['prize_code'],
                'order_type' => $order_type,
                'order_list_id' => $order_list_id,
            ];
            #增加销量
            $res[] = GoodsList::field('surplus_stock')
                ->where(['id' => $special_prize['id']])
                ->dec('surplus_stock')
                ->update();
            #新增奖品列表
            $res[] = OrderList::insert($order_goods);
        } else {
            $res[] = 1;
        }
        return $res;
    }

    /**
     * 特殊奖品开奖 LAST 最终赏 全局赏
     * @param $order 订单信息
     * @param $first_count
     */
    protected function special_prize_notice($order, $first_count)
    {
        $res = [];
        $goods_id = $order['goods_id'];
        $num = $order['num'];
        $order_type = $order['order_type'];
        #特殊奖品存在
        $special_prize = GoodsList::where('goods_id', '=', $goods_id)
            ->where('num', '=', $num)
            ->where('surplus_stock', '>', 0)
            ->where('shang_id', 'in', self::$shang_give_arr)
            ->select()->toArray();
        $surplus_give_stock = $special_prize ? array_sum(array_column($special_prize, 'surplus_stock')) : 0;
        if ($special_prize && $surplus_give_stock > 0) {
            #所有奖品信息
            $all_order_list = OrderList::field('id,user_id')
                ->where('goods_id', '=', $goods_id)
                ->where('num', '=', $num)
                ->where('order_type', '=', $order_type)
                ->where('shang_id', 'between', self::$shang_prize_id)
                ->order('id asc')
                ->select()->toArray();
            $order_goods = [];
            foreach ($special_prize as $k => $v) {
                if ($v['shang_id'] == 4) { #全局赏

                    for ($surplus_stock_i = 0; $surplus_stock_i < $v['surplus_stock']; $surplus_stock_i++) {
                        $overall_order_list = $all_order_list;
                        shuffle($overall_order_list);
                        shuffle($overall_order_list);
                        $prize_info = $overall_order_list[0];
                        $user_id = $prize_info['user_id'];
                        #特殊赏中奖订单id
                        $order_list_id = $prize_info['id'];
                        #中奖奖项
                        $ordinary_prize_info = $v;
                        $order_goods[] = [
                            'order_id' => 0,
                            'user_id' => $user_id,
                            'status' => 0, #0未操作 1选择兑换 2选择发货
                            'goods_id' => $goods_id,
                            'num' => $num,
                            'shang_id' => $ordinary_prize_info['shang_id'],
                            'goodslist_id' => $ordinary_prize_info['id'],
                            'goodslist_title' => $ordinary_prize_info['title'],
                            'goodslist_imgurl' => $ordinary_prize_info['imgurl'],
                            'goodslist_price' => $ordinary_prize_info['price'],
                            'goodslist_money' => $ordinary_prize_info['money'],
                            'goodslist_type' => $ordinary_prize_info['goods_type'],
                            'goodslist_sale_time' => $ordinary_prize_info['sale_time'],
                            'addtime' => time(),
                            'prize_code' => $ordinary_prize_info['prize_code'],
                            'order_type' => $order_type,
                            'order_list_id' => $order_list_id,
                        ];
                        #减少库存
                        $res[] = GoodsList::field('surplus_stock')
                            ->where(['id' => $ordinary_prize_info['id']])
                            ->dec('surplus_stock')
                            ->update();
                    }
                } else {
                    if ($v['shang_id'] == 2) { #LAST赏
                        $last_order_list = array_slice($all_order_list, (int) $first_count);
                        shuffle($last_order_list);
                        shuffle($last_order_list);
                        $prize_info = $last_order_list[0];
                        #中奖用户id
                        $user_id = $prize_info['user_id'];
                        #特殊赏中奖订单id
                        $order_list_id = $prize_info['id'];
                        #中奖奖项
                        $ordinary_prize_info = $v;
                    } elseif ($v['shang_id'] == 3) { #最终赏
                        $end_order_list = $all_order_list;
                        $prize_info = end($end_order_list);
                        #中奖用户id
                        $user_id = $prize_info['user_id'];
                        #特殊赏中奖订单id
                        $order_list_id = $prize_info['id'];
                        #中奖奖项
                        $ordinary_prize_info = $v;
                    }
                    $order_goods[] = [
                        'order_id' => 0,
                        'user_id' => $user_id,
                        'status' => 0, #0未操作 1选择兑换 2选择发货
                        'goods_id' => $goods_id,
                        'num' => $num,
                        'shang_id' => $ordinary_prize_info['shang_id'],
                        'goodslist_id' => $ordinary_prize_info['id'],
                        'goodslist_title' => $ordinary_prize_info['title'],
                        'goodslist_imgurl' => $ordinary_prize_info['imgurl'],
                        'goodslist_price' => $ordinary_prize_info['price'],
                        'goodslist_money' => $ordinary_prize_info['money'],
                        'goodslist_type' => $ordinary_prize_info['goods_type'],
                        'goodslist_sale_time' => $ordinary_prize_info['sale_time'],
                        'addtime' => time(),
                        'prize_code' => $ordinary_prize_info['prize_code'],
                        'order_type' => $order_type,
                        'order_list_id' => $order_list_id,
                    ];
                    #减少库存
                    $res[] = GoodsList::field('surplus_stock')
                        ->where(['id' => $ordinary_prize_info['id']])
                        ->dec('surplus_stock')
                        ->update();
                }
            }
            #新增奖品列表
            $res[] = OrderList::insertAll($order_goods);
        } else {
            $res[] = 1;
        }
        return $res;
    }

    /**冲锋***/
    public function chong_prize($order = [])
    {
        $goods_id = $order['goods_id'];
        $num = $order['num']; // 箱号
        $order_type = $order['order_type'];
        // $where = [];
        // $where[] = ['goods_id', '=', $goods_id];
        // $where[] = ['num','=', $num];
        // $num_one = Order::where($where)->field('sum(`prize_num`) as total, user_id')->group('user_id')->order('total desc')->find();
        // $user_id = $num_one['user_id'];

        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', $num];
        $where[] = ['shang_id', 'between', self::$shang_prize_id];
        $field = 'user_id, count(`id`) count_num';
        $ranks = OrderList::where($where)->field($field)->group('user_id')->order('count_num desc')->paginate(['list_rows' => 100, 'query' => request()->param()]);
        $user_list = $ranks->toArray()['data'];
        $user_id = $user_list[0]['user_id'];

        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', $num];
        $where[] = ['shang_id', '=', '6'];
        $where[] = ['surplus_stock', '>', 0];
        $goodslist = GoodsList::where($where)->find();
        $res = [];
        if (!empty($goodslist)) {
            $order_goods = [
                'order_id' => 0,
                'user_id' => $user_id,
                'status' => 0, #0未操作 1选择兑换 2选择发货
                'goods_id' => $goods_id,
                'num' => $num,
                'shang_id' => $goodslist['shang_id'],
                'goodslist_id' => $goodslist['id'],
                'goodslist_title' => $goodslist['title'],
                'goodslist_imgurl' => $goodslist['imgurl'],
                'goodslist_price' => $goodslist['price'],
                'goodslist_money' => $goodslist['money'],
                'goodslist_type' => $goodslist['goods_type'],
                'goodslist_sale_time' => $goodslist['sale_time'],
                'addtime' => time(),
                'prize_code' => $goodslist['prize_code'],
                'order_type' => $order_type,
                'order_list_id' => $order['id'],
            ];
            #减少库存
            $res[] = $dd  = GoodsList::field('surplus_stock')
                ->where(['id' => $goodslist['id']])
                ->dec('surplus_stock')
                ->update();
            $res[] = $rr = OrderList::insert($order_goods);
        } else {
            // $res[] = ;
        }
        return $res;
    }

    /**
     * 爬塔处理
     * @param int $user_id
     * @param int $order_id
     * @param int $goods_id
     */
    public function pata_drawprize_notice($user_id = 0, $order_id = 0, $goods_id = 0, $num = 0, $pay_type = 1)
    {
        $res = [];
        $order = Order::where(['id' => $order_id])
            ->where(['user_id' => $user_id])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => $num])
            ->where(['status' => 0])
            ->find();
        if ($order) {
            #改变状态
            $res[] = Order::field('status,pay_time')
                ->where(['id' => $order['id']])
                ->update([
                    'status' => 1,
                    'pay_time' => time(),
                ]);
            $res[] = ProfitRank::insert([
                'user_id' => $user_id,
                'order_num' => $order['order_num'],
                'change_money' => $order['order_total'],
                'content' => '购买爬塔盒子' . $order['goods_title'],
                'pay_type' => $pay_type, #1微信 2支付宝
                'addtime' => time(),
            ]);
            #扣余额
            if ($order['use_money'] > 0) {
                $res[] = User::changeMoney($order['user_id'], -$order['use_money'], 3, '购买爬塔盒子' . $order['goods_title']);
            }

            #赠送欧气
            $ouqi_num = floor($order['order_total'] / 10);
            if ($ouqi_num > 0) {
                $tt = User::changeOuQi($user_id, $ouqi_num, 2, '爬塔消费赠送');
                $ss = User::ou_qi_level_up($user_id, $ouqi_num, 2);
                $res = array_merge($res, $tt);
            }
            $score_num = round(($order['order_total'] / 100), 2);
            User::changeScore($user_id, $score_num, 2, '爬塔消费赠送');
            #判断一下优惠券
            if (!empty($order['coupon_id'])) {
                $res[] = CouponReceiveModel::where(['id' => $order['coupon_id'], 'status' => 0])->update(['status' => 1]);
            }

            #分销奖励
            $res[] = User::distribution($order);

            #分销奖励
            #开奖==================================================
            $res[] = $this->pata_kaijiang($order);
            #开奖==================================================
            #判断是否发积分 发券
            // $res[] = User::is_integral_coupon($order);
            #判断是否发积分

        } else {
            $res[] = 0;
        }
        return $res;
    }


    // 爬塔开奖
    public function pata_kaijiang($order = [])
    {
        $order_type = $order['order_type']; // 11爬塔
        $goods_id = $order['goods_id'];
        $pata_num = $order['num']; //塔层级
        $user_id = $order['user_id'];
        $order_id = $order['id'];
        $prize_num = $order['prize_num'];
        $w = [];
        $w[] = ['goods_id', '=', $goods_id];
        $w[] = ['status', '=', '1'];
        $w[] = ['num', '=', $pata_num];
        $w[] = ['prize_type', '<', 4];
        $field = "id,title,imgurl,price,gailv,stock,shang_id,prize_type,goods_type,sale_time, prize_code,money"; //goods_type 1现货 2预售
        $goodslist = GoodsList::getAllList($w, $field, 'stock desc');
        $total_stock = GoodsList::where($w)->sum('stock');            //总库存
        //获取奖池
        $num = 0;
        $tempdata = array();
        $goodslist = $goodslist->toArray();
        if (empty($goodslist)) {
            return 0;
        }
        $yu = $total_stock - $prize_num;
        foreach ($goodslist as $one) {
            if ($yu < 5) {
                $w = [];
                $w[] = ['status', '=', '1'];
                $w[] = ['id', '=', $one['id']];
                $w[] = ['num', '=', $pata_num];
                GoodsList::where($w)->inc('stock', (int) $one['gailv'])->update();
            }
            if ($one['stock'] < 1) {
                continue;
            }
            $num += $one['stock'];
            for ($i = 0; $i < $one['stock']; $i++) {
                $tempdata[] = $one;
            }
        }
        $tempdata = shuffle_assoc($tempdata);
        $zhong = [];
        // if ($pata_num < 10) {
        if ($prize_num == 1) {
            //开奖
            $use = rand(0, $num - 1);
            $one = $tempdata[$use];
            $zhong = [$one];
        } elseif ($prize_num > 1) {
            $rand_array = range(0, $num - 1);
            shuffle($rand_array);  //调用现成的数组随机排列函数
            $ress = array_slice($rand_array, 0, $prize_num); //截取前$limit个
            for ($i = 0; $i < $prize_num; $i++) {
                $zhong[$i] = $tempdata[$ress[$i]];
            }
        }
        // } else {
        //     $use = rand(0, $num - 1);
        //     $one = $tempdata[$use];
        //     $zhong = [$one];
        // }
        $goodslist_id = [];
        $time = time();
        foreach ($zhong as $k => $v) {
            $luck_no = OrderList::field('id')
                ->where('goods_id', '=', $goods_id)
                ->where('num', '=', $pata_num)
                ->where('order_type', '=', $order_type)
                ->order('id desc')
                ->value('luck_no');
            $luck_no++;
            #新增记录
            $save_prize_info = [
                'order_id' => $order_id,
                'user_id' => $user_id,
                'status' => 0, #0未操作 1选择兑换 2选择发货
                'goods_id' => $goods_id,
                'num' => $pata_num,
                'prize_type' => $v['prize_type'],
                'shang_id' => $v['shang_id'],
                'goodslist_id' => $v['id'],
                'goodslist_title' => $v['title'],
                'goodslist_imgurl' => $v['imgurl'],
                'goodslist_price' => $v['price'],
                'goodslist_type' => $v['goods_type'], //'1现货 2预售'
                'goodslist_sale_time' => $v['sale_time'],
                'addtime' => $time,
                'goodslist_money' => $v['money'],
                'prize_code' => $v['prize_code'],
                'order_type' => $order_type,
                'luck_no' => $luck_no ?? 1,
            ];
            $goodslist_id[$k] = $v['id'];
            $res[] = OrderList::insert($save_prize_info);
        }
        $goodslist_ids = array_count_values($goodslist_id);
        foreach ($goodslist_ids as $k => $v) {
            GoodsList::where(['id' => $k])->dec('stock', $v)->update();
        }
        $goodslist_ids = array_keys($goodslist_ids);
        //晋级商品
        $w = [];
        $w[] = ['goods_id', '=', $goods_id];
        $w[] = ['prize_type', '=', 2]; //晋级
        $w[] = ['num', '=', $pata_num];
        $w[] = ['status', '=', 1];
        $goodslist = GoodsList::getInfo($w, 'id,prize_type,num');
        $is_change = 1;
        $goodslist_id_two = 0;
        if (!empty($goodslist) && in_array($goodslist['id'], $goodslist_ids)) {
            //添加升级记录
            $is_change = 2;
            $goodslist_id_two = $goodslist['id'];
        }
        //降级商品
        $w = [];
        $w[] = ['goods_id', '=', $goods_id];
        $w[] = ['prize_type', '=', 3]; //3=降级奖品
        $w[] = ['num', '=', $pata_num];
        $w[] = ['status', '=', 1];
        $goodslist = GoodsList::getInfo($w, 'id, prize_type, num');
        if (!empty($goodslist) && in_array($goodslist['id'], $goodslist_ids)) {
            //添加降级记录
            if ($is_change == 1) {
                $is_change = 3;
                $goodslist_id_two = $goodslist['id'];
            } else {
                $is_change = 4;
            }
        }
        if ($is_change == 2) { //升级
            // 是否首次闯关
            //         $ww = [];
            // 		$ww[] = ['user_id','=',$user_id];
            // 		$ww[] = ['goods_id','=',$goods_id];
            // 		$ww[] = ['num','=',$pata_num];
            // 		$check_first = ClimbUser::getInfo($ww,'id,user_id,num');
            // 		if (!empty($check_first)) {
            // 		    $where = [];
            //             $where[] = ['goods_id', '=', $goods_id];
            //             $where[] = ['prize_type', '=', 5]; //5=首通奖励
            //             $where[] = ['num', '=', $pata_num];
            //             $where[] = ['status', '=', 1];
            //             $first_prize = GoodsList::getInfo($where);
            //             if (!empty($first_prize)) {
            //                 $first_prize_info = [
            //                     'order_id' => $order_id,
            //                     'user_id' => $user_id,
            //                     'status' => 0,#0未操作 1选择兑换 2选择发货
            //                     'goods_id' => $goods_id,
            //                     'num' => $pata_num,
            //                     'prize_type' => $first_prize['prize_type'],
            //                     'shang_id' => $first_prize['shang_id'],
            //                     'goodslist_id' => $first_prize['id'],
            //                     'goodslist_title' => $first_prize['title'],
            //                     'goodslist_imgurl' => $first_prize['imgurl'],
            //                     'goodslist_price' => $first_prize['price'],
            //                     'goodslist_type' => $first_prize['goods_type'], //'1现货 2预售'
            //                     'goodslist_sale_time' => $first_prize['sale_time'],
            //                     'addtime' => time(),
            //                     'prize_code' => $first_prize['prize_code'],
            //                     'order_type' => $order_type,
            //                     'luck_no' => $luck_no,
            //                 ];
            //                 $res[] = OrderList::insert($first_prize_info);
            //             }
            // 		}

            $pata_num++;
            $w = [];
            $w[] = ['id', '=', $goods_id];
            $w[] = ['type', '=', '11'];
            $goods = Goods::getinfo($w);
            // if (empty($goods)) {
            //     $res[] = 0;
            // }
            //更新当前层级
            // if ($pata_num == 11) {
            //     $pata_num = 1;
            // }
            // $arr = [];
            // $arr['user_id'] = $user_id;
            // $arr['goods_id'] = $goods_id;
            // $arr['order_id'] = $order_id;
            // $arr['goodslist_id'] = $goodslist_id_two;
            // $arr['num'] = $pata_num;
            // $arr['day'] = date("Y-m-d");
            // $arr['addtime'] = $time;
            // $res[] = ClimbUser::insert($arr);
            $top_num = $goods['floors_num'] + 1;
            if ($pata_num == $top_num) {
                //  最后一层 更新登顶记录
                $arr = [];
                $arr['user_id'] = $user_id;
                $arr['goods_id'] = $goods_id;
                $arr['number'] = 1;
                $res[] = ClimbRank::insert($arr);
                // 通关大奖
                $w = [];
                $w[] = ['goods_id', '=', $goods_id];
                $w[] = ['status', '=', '1'];
                $w[] = ['prize_type', '=', 4];
                $goodslist = GoodsList::getAllList($w, $field, 'stock desc');
                $total_stock = GoodsList::where($w)->sum('stock');            //总库存
                //获取奖池
                $num = 0;
                $tempdata = array();
                $goodslist = $goodslist->toArray();
                if (empty($goodslist)) {
                    return 0;
                }
                $yu = $total_stock - $prize_num;
                foreach ($goodslist as $one) {
                    if ($yu < 5) {
                        $w = [];
                        $w[] = ['status', '=', '1'];
                        $w[] = ['id', '=', $one['id']];
                        GoodsList::where($w)->inc('stock', (int) $one['gailv'])->update();
                    }
                    if ($one['stock'] < 1) {
                        continue;
                    }
                    $num += $one['stock'];
                    for ($i = 0; $i < $one['stock']; $i++) {
                        $tempdata[] = $one;
                    }
                }
                $tempdata = shuffle_assoc($tempdata);
                $zhong = [];
                $use = rand(0, $num - 1);
                $one = $tempdata[$use];
                $zhong = [$one];
                $goodslist_id = [];
                $time = time();
                foreach ($zhong as $k => $v) {
                    $save_prize_info = [
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                        'status' => 0, #0未操作 1选择兑换 2选择发货
                        'goods_id' => $goods_id,
                        'num' => 11,
                        'prize_type' => $v['prize_type'],
                        'shang_id' => $v['shang_id'],
                        'goodslist_id' => $v['id'],
                        'goodslist_title' => $v['title'],
                        'goodslist_imgurl' => $v['imgurl'],
                        'goodslist_price' => $v['price'],
                        'goodslist_type' => $v['goods_type'], //'1现货 2预售'
                        'goodslist_sale_time' => $v['sale_time'],
                        'addtime' => $time,
                        'goodslist_money' => $v['money'],
                        'prize_code' => $v['prize_code'],
                        'order_type' => $order_type,
                        'luck_no' => 0,
                    ];
                    $goodslist_id[$k] = $v['id'];
                    $res[] = OrderList::insert($save_prize_info);
                }
                $goodslist_ids = array_count_values($goodslist_id);
                foreach ($goodslist_ids as $k => $v) {
                    $res[] = GoodsList::where(['id' => $k])->dec('stock', $v)->update();
                }
                $pata_num = 1;
            }
            $arr = [];
            $arr['user_id'] = $user_id;
            $arr['goods_id'] = $goods_id;
            $arr['order_id'] = $order_id;
            $arr['goodslist_id'] = $goodslist_id_two;
            $arr['num'] = $pata_num;
            $arr['day'] = date("Y-m-d");
            $arr['addtime'] = $time;
            $res[] = ClimbUser::insert($arr);
        } elseif ($is_change == 3) { // 降级操作
            if ($pata_num < 2) {
                $pata_num = 1;
            } else {
                $pata_num--;
            }
            $arr = [];
            $arr['user_id'] = $user_id;
            $arr['goods_id'] = $goods_id;
            $arr['order_id'] = $order_id;
            $arr['goodslist_id'] = $goodslist_id_two;
            $arr['num'] = $pata_num;
            $arr['day'] = date("Y-m-d");
            $arr['addtime'] = $time;
            $res[] = ClimbUser::insert($arr);
        }
        return $res;
    }


    /**
     * 无限赏开始抽赏======================================================
     * @param int $user_id 会员id
     * @param int $order_id 订单ID
     * @param int $box_id 盲盒id
     */
    public function infinite_drawprize_notice($user_id = 0, $order_id = 0, $goods_id = 0, $pay_type = 1)
    {

        $res = [];
        $order = Order::where(['id' => $order_id])
            ->where(['user_id' => $user_id])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->where(['status' => 0])
            ->find();
        if ($order) {
            #改变状态
            $res[] = Order::field('status,pay_time')
                ->where(['id' => $order['id']])
                ->update([
                    'status' => 1,
                    'pay_time' => time(),
                ]);
            $res[] = ProfitRank::insert([
                'user_id' => $user_id,
                'order_num' => $order['order_num'],
                'change_money' => $order['order_total'],
                'content' => '购买无限赏盒子' . $order['goods_title'],
                'pay_type' => $pay_type, #1微信 2支付宝
                'addtime' => time(),
            ]);

            #扣余额
            if ($order['use_money'] > 0) {
                $res[] = User::changeMoney($order['user_id'], -$order['use_money'], 3, '购买盒子' . $order['goods_title']);
            }
            #扣潮币
            if ($order['use_integral'] > 0) {
                $res[] = User::changeIntegral($order['user_id'], -$order['use_integral'], 2, '购买盒子' . $order['goods_title']);
            }

            # 赠送欧气
            $ouqi_num = floor($order['order_total'] / 10);
            if ($ouqi_num > 0) {
                $tt = User::changeOuQi($user_id, $ouqi_num, 2, '消费赠送');
                $ss = User::ou_qi_level_up($user_id, $ouqi_num, 2);
                $res = array_merge($res, $tt);
            }
            $score_num = round(($order['order_total'] / 100), 2);
            User::changeScore($user_id, $score_num, 2, '消费赠送');
            #判断一下优惠券
            if (!empty($order['coupon_id'])) {
                $coupon = CouponReceiveModel::where(['id' => $order['coupon_id'], 'status' => 0])->update(['status' => 1]);
            }

            #分销奖励
            $res[] = User::distribution($order);

            #分销奖励
            #开奖==================================================
            $res[] = $ress = $this->infinite_drawprize($order);
            #开奖==================================================
            #判断是否发积分 发券
            $res[] = User::is_integral_coupon($order);
            #判断是否发积分

        } else {
            $res[] = 0;
        }

        return $res;
    }

    /**
     * 无限赏开奖逻辑
     * @param $order 订单信息
     */
    protected function infinite_drawprize($order = [])
    {
        $user_id = $order['user_id']; #用户ID
        $order_id = $order['id']; #订单ID
        $goods_id = $order['goods_id']; #盒子ID
        $prize_num = $order['prize_num']; #抽奖数量
        $order_type = $order['order_type']; #订单类型
        $whe = [];
        $whe[] = ['id', '=', $order['goods_id']];
        $infinite_goods = Goods::getInfo($whe, 'type');

        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', 0];
        $where[] = ['gailv', '>', 0];
        if ($infinite_goods['type'] == 9 && $order['is_mibao'] == 1) {
            //秘宝池
            $where[] = ['lian_ji_type', '=', 1];
        } else {
            //普通
            $where[] = ['lian_ji_type', '=', 0];
        }

        #查找奖品
        $goodslist = GoodsList::field('id, shang_id, title,imgurl, price, money, goods_type, goods_type, sale_time, prize_code, stock,gailv')
            ->where($where)
            ->select()->toArray();
        if ($goodslist) {
            #组合中奖商品
            // $all_goods_id = [];
            // foreach ($goodslist as $value) {
            //     $real_pro = $value['real_pro'] * 10000;
            //     for ($i = 1; $i <= $real_pro; $i++) {
            //         $all_goods_id[] = $value['id'];
            //     }
            // }
            $num = 0;
            $total_stock = GoodsList::where($where)->sum('stock');            //总库存
            $yu = $total_stock - $prize_num;
            foreach ($goodslist as $one) {
                if ($yu < 100) {
                    $w = [];
                    // $w[] = ['status', '=', '1'];
                    $w[] = ['id', '=', $one['id']];
                    $yy = GoodsList::where($w)->inc('stock', (int) $one['gailv'])->update();
                }
                if ($one['stock'] < 1) {
                    continue;
                }
                $num += $one['stock'];
                for ($i = 0; $i < $one['stock']; $i++) {
                    $tempdata[] = $one;
                }
            }
            $tempdata = shuffle_assoc($tempdata);
            $zhong = [];
            if ($prize_num == 1) {
                //开奖
                $use = rand(0, $num - 1);
                $one = $tempdata[$use];
                $zhong = [$one];
            } elseif ($prize_num > 1) {
                $rand_array = range(0, $num - 1);
                shuffle($rand_array);  //调用现成的数组随机排列函数
                $ress = array_slice($rand_array, 0, $prize_num); //截取前$limit个
                for ($i = 0; $i < $prize_num; $i++) {
                    $zhong[$i] = $tempdata[$ress[$i]];
                }
            }
            $goodslist_id = [];
            foreach ($zhong as $k => $v) {
                $luck_no = OrderList::field('id')
                    ->where('goods_id', '=', $goods_id)
                    ->where('num', '=', 0)
                    ->where('order_type', '=', $order_type)
                    ->order('id desc')
                    ->value('luck_no');
                $luck_no++;
                #新增记录
                $save_prize_info = [
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'status' => 0, #0未操作 1选择兑换 2选择发货
                    'goods_id' => $goods_id,
                    'num' => 0,
                    'shang_id' => $v['shang_id'],
                    'goodslist_id' => $v['id'],
                    'goodslist_title' => $v['title'],
                    'goodslist_imgurl' => $v['imgurl'],
                    'goodslist_price' => $v['price'],
                    'goodslist_money' => $v['money'],
                    'goodslist_type' => $v['goods_type'],
                    'goodslist_sale_time' => $v['sale_time'],
                    'addtime' => time(),
                    'prize_code' => $v['prize_code'],
                    'order_type' => $order_type,
                    'luck_no' => $luck_no,
                ];
                $goodslist_id[$k] = $v['id'];
                $res[] = OrderList::insert($save_prize_info);
            }
            $my_res = array_count_values($goodslist_id);
            foreach ($my_res as $k => $v) {
                $res[] = GoodsList::where(['id' => $k])->dec('stock', $v)->update();
            }

            // for ($i = 0; $i < $prize_num; $i++) {
            //     #随机打乱
            //     shuffle($all_goods_id);
            //     shuffle($all_goods_id);
            //     $prize_id = $all_goods_id[0];
            //     $prize_info = GoodsList::where(['id' => $prize_id])->find();
            //     #编号
            //     $luck_no = OrderList::field('id')
            //         ->where('goods_id', '=', $goods_id)
            //         ->where('num', '=', 0)
            //         ->where('order_type', '=', $order_type)
            //         ->order('id desc')
            //         ->value('luck_no');
            //     $luck_no++;
            //     #新增记录
            //     $save_prize_info = [
            //         'order_id' => $order_id,
            //         'user_id' => $user_id,
            //         'status' => 0,#0未操作 1选择兑换 2选择发货
            //         'goods_id' => $goods_id,
            //         'num' => 0,
            //         'shang_id' => $prize_info['shang_id'],
            //         'goodslist_id' => $prize_info['id'],
            //         'goodslist_title' => $prize_info['title'],
            //         'goodslist_imgurl' => $prize_info['imgurl'],
            //         'goodslist_price' => $prize_info['price'],
            //         'goodslist_money' => $prize_info['money'],
            //         'goodslist_type' => $prize_info['goods_type'],
            //         'goodslist_sale_time' => $prize_info['sale_time'],
            //         'addtime' => time(),
            //         'prize_code' => $prize_info['prize_code'],
            //         'order_type' => $order_type,
            //         'luck_no' => $luck_no,
            //     ];
            //     #入库===
            //     $res[] = OrderList::insert($save_prize_info);
            // }

            //去除秘宝池次数
            if ($infinite_goods['type'] == 9 && $order['is_mibao'] == 1) {
                User::where('id', $user_id)->dec('mb_number', $prize_num)->update();
            }

            //计算怒气值
            $this->rage($goods_id, $order_id, $user_id);

            //领主
            $this->ling_zhu($order, $order_id);
            //连击赏
            if ($infinite_goods['type'] == 9 && $order['is_mibao'] == 0) {
                $this->lian_ji($order, $order_id);
            }
        } else {
            $res[] = 0;
        }
        return $res;
    }

    //计算怒气值
    public function rage($goods_id, $order_id, $user_id)
    {
        $order_list = OrderList::field('id')->where(['order_id' => $order_id])->find();
        if (!$order_list) {
            return false;
        }
        try {
            $goods = Goods::field('id')->field('rage_is,rage,item_card_id')->where(['id' => $goods_id])->find();
            if ($goods['rage_is'] == 1 && $goods['rage'] > 0 && $goods['item_card_id'] > 0) {
                $order = Order::field('order_total')->where(['id' => $order_id])->find();
                if ($order['order_total'] > 0) {
                    //获取奖品总价值
                    $out_price_sum = OrderList::where(['order_id' => $order_id])->sum('goodslist_money');
                    $rage_number = bcsub($order['order_total'], "$out_price_sum", 2);
                    $user_rage = Db::name('user_rage')->field('id,rage')->where(['user_id' => $user_id, 'goods_id' => $goods_id])->find();

                    if ($user_rage) {
                        $rage_number2 = bcadd((string) ($user_rage['rage']), "$rage_number", 2);
                        if ($rage_number2 >= $goods['rage']) {
                            //赠送道具卡
                            $item_card = ItemCard::field('id,title')->where(['id' => $goods['item_card_id']])->find();
                            if ($item_card) {
                                Db::name('user_item_card')->insert(['user_id' => $user_id, 'item_card_id' => $item_card['id'], 'title' => $item_card['title'], 'status' => 1, 'addtime' => time(), 'updatetime' => time()]);
                            }
                            Db::name('user_rage')->where(['user_id' => $user_id, 'goods_id' => $goods_id])->update(['rage' => 0, 'updatetime' => time()]);
                        } else {
                            Db::name('user_rage')->where(['user_id' => $user_id, 'goods_id' => $goods_id])->update(['rage' => $rage_number2, 'updatetime' => time()]);
                        }
                    } else {
                        Db::name('user_rage')->insert(['user_id' => $user_id, 'goods_id' => $goods_id, 'rage' => $rage_number, 'addtime' => time(), 'updatetime' => time()]);
                    }
                }
            }
        } catch (\Exception $e) { }
    }

    //领主
    public function ling_zhu($order, $order_id)
    {
        //是否开启领主模式
        $whe = [];
        $whe[] = ['id', '=', $order['goods_id']];
        $infinite_goods = Goods::getInfo($whe, 'type,lingzhu_is,lingzhu_fan,lingzhu_shang_id,king_user_id');
        if ($infinite_goods['type'] != 8) {
            return false;
        }

        if ($infinite_goods['lingzhu_is'] == 1) {
            $whe2 = [];
            $whe2[] = ['order_id', '=', $order_id];
            $order_list = OrderList::getAllList($whe2, 'id,shang_id,user_id,goods_id', 'id asc');
            foreach ($order_list as $k => $v) {
                if ($v['shang_id'] == $infinite_goods['lingzhu_shang_id']) {
                    // 查找当前池子是否有领主
                    if ($infinite_goods['king_user_id'] != 0) {
                        Db::name('goods_king_rank')->where([['user_id', '=', $infinite_goods['king_user_id']], ['goods_id', '=', $v['goods_id']]])->order('id', 'desc')->limit(1)->update(['end_time' => time()]);
                    }

                    //新的领主
                    Goods::where(['id' => $v['goods_id']])->update(['king_user_id' => $v['user_id']]);
                    //多少发晋升领主
                    $luck_no = OrderList::where([['goods_id', '=', $v['goods_id']], ['id', '<=', $v['id']]])->count();
                    $rank = [
                        'user_id' => $v['user_id'],
                        'goods_id' => $v['goods_id'],
                        'count' => $luck_no,
                        'order_list_id' => $v['id'],
                        'addtime' => time(),
                    ];

                    $result = Db::name('goods_king_rank')->insert($rank);
                } else {
                    // 查找当前池子是否有领主
                    $infinite_goods = Goods::getInfo($whe, 'lingzhu_is,lingzhu_fan,lingzhu_shang_id,king_user_id');

                    if ($infinite_goods['king_user_id'] != 0) {

                        Db::name('goods_king_rank')->where([['user_id', '=', $infinite_goods['king_user_id']], ['goods_id', '=', $v['goods_id']]])->order('id', 'desc')->limit(1)->inc('z_nums', 1)->update();
                        $king_money = $infinite_goods['lingzhu_fan'];

                        if ($king_money && $king_money > 0) {

                            Db::name('goods_king_rank')->where([['user_id', '=', $infinite_goods['king_user_id']], ['goods_id', '=', $v['goods_id']]])->order('id', 'desc')->limit(1)->inc('money', floatval($king_money))->update();

                            // User::changeIntegral($infinite_goods['king_user_id'], $king_money, 4, '领主收益');
                            User::changeScore($infinite_goods['king_user_id'], $king_money, 5, '领主收益');
                        }
                    }
                }
            }
        }
    }

    //连击赏
    public function lian_ji($order, $order_id)
    {
        //是否是连击赏
        $whe = [];
        $whe[] = ['id', '=', $order['goods_id']];
        $infinite_goods = Goods::getInfo($whe, 'type,lian_ji_num,lian_ji_shang_id');
        if ($infinite_goods['type'] != 9) {
            return false;
        }
        if ($order['is_mibao'] == 1) {
            //减少秘宝池次数
            User::field('mb_number')->where(['id' => $order['user_id']])->dec('mb_number', $order['prize_num'])->update();
        }
        $whe2 = [];
        $whe2[] = ['order_id', '=', $order_id];
        $order_list = OrderList::getAllList($whe2, 'id,shang_id,goods_id,user_id', 'id asc');
        foreach ($order_list as $k => $v) {
            //是否已有连击
            $user_goods_lian_ji = Db::name('user_goods_lian_ji')->where([['user_id', '=', $v['user_id']], ['goods_id', '=', $v['goods_id']]])->whereNull('deltime')->order('id', 'desc')->find();

            if ($v['shang_id'] == $infinite_goods['lian_ji_shang_id']) {

                if ($infinite_goods['lian_ji_num'] != 0 && $infinite_goods['lian_ji_shang_id'] != 0) {

                    if ($user_goods_lian_ji) {
                        Db::name('user_goods_lian_ji')->field('number,updatetime')->where([['user_id', '=', $v['user_id']], ['goods_id', '=', $v['goods_id']]])->whereNull('deltime')->order('id', 'desc')->inc('number', 1)->update(['updatetime' => time()]);
                        //连击次数是否满足条件
                        $lian_ji_number = Db::name('user_goods_lian_ji')->where([['user_id', '=', $v['user_id']], ['goods_id', '=', $v['goods_id']]])->whereNull('deltime')->order('id', 'desc')->limit(1)->value('number');
                        if ($lian_ji_number && $lian_ji_number >= $infinite_goods['lian_ji_num']) {
                            //赠送秘宝池次数
                            User::field('mb_number')->where(['id' => $v['user_id']])->inc('mb_number', 1)->update();
                            //清空连击次数
                            Db::name('user_goods_lian_ji')->field('number,updatetime')->where([['user_id', '=', $v['user_id']], ['goods_id', '=', $v['goods_id']]])->whereNull('deltime')->order('id', 'desc')->update(['number' => 0, 'updatetime' => time()]);
                        }
                    } else {
                        Db::name('user_goods_lian_ji')->insert(['user_id' => $v['user_id'], 'goods_id' => $v['goods_id'], 'number' => 1, 'addtime' => time(), 'updatetime' => time()]);
                    }
                }
            } else {
                if ($user_goods_lian_ji) {
                    Db::name('user_goods_lian_ji')->field('number,updatetime')->where([['user_id', '=', $v['user_id']], ['goods_id', '=', $v['goods_id']]])->whereNull('deltime')->order('id', 'desc')->update(['number' => 0, 'updatetime' => time()]);
                } else {
                    Db::name('user_goods_lian_ji')->insert(['user_id' => $v['user_id'], 'goods_id' => $v['goods_id'], 'number' => 0, 'addtime' => time(), 'updatetime' => time()]);
                }
            }
        }
    }

    /**
     * 抽卡机抽奖逻辑
     * @param int $user_id
     * @param int $order_id
     * @param int $goods_id
     */
    public function cardextractor_drawprize_notice($user_id = 0, $order_id = 0, $goods_id = 0)
    {
        // $res = [];
        // $order = Order::where(['id' => $order_id])
        //     ->where(['user_id' => $user_id])
        //     ->where(['goods_id' => $goods_id])
        //     ->where(['num' => 0])
        //     ->where(['status' => 0])
        //     ->where(['order_type' => 4])
        //     ->find();
        // // dd($order);
        // if ($order) {
        //     #改变状态
        //     $res[] = Order::field('status,pay_time')
        //         ->where(['id' => $order['id']])
        //         ->update([
        //             'status' => 1,
        //             'pay_time' => time(),
        //         ]);
        //     # 实时营收
        //     $res[] = ProfitRank::insert([
        //         'user_id' => $user_id,
        //         'order_num' => $order['order_num'],
        //         'change_money' => $order['order_total'], // 订单总金额
        //         'content' => '购买盒子'.$order['goods_title'],
        //         'pay_type' => 1,#1微信 2支付宝
        //         'addtime' => time(),
        //     ]);
        //     #扣余额
        //     if ($order['use_money'] > 0) {
        //         $res[] = User::changeMoney($order['user_id'], -$order['use_money'], 3, '购买盒子' . $order['goods_title']);
        //     }
        //     #扣潮币
        //     if ($order['use_integral'] > 0) {
        //         $res[] = User::changeIntegral($order['user_id'], -$order['use_integral'], 2, '购买盒子' . $order['goods_title']);
        //     }
        //     #判断一下优惠券
        //     if (!empty($order['coupon_id'])) {
        //         $coupon = CouponReceiveModel::where(['id' => $order['coupon_id'], 'status' => 0])->update(['status' => 1]);
        //     }
        //     #判断是否发积分 发券
        //     $res[] = User::is_integral_coupon($order);
        //     #判断是否发积分

        //     #分销奖励
        //     $res[] = User::distribution($order);
        //     #分销奖励

        //     #开奖==================================================
        //     $res[] = $this->cardextractor_drawprize($order);
        //     #开奖==================================================

        // } else {
        //     $res[] = 0;
        // }
        // return $res;
    }

    /**
     * 抽卡机开奖
     * @param array $order
     */
    public function cardextractor_drawprize($order = [])
    {
        $user_id = $order['user_id']; #用户ID
        $order_id = $order['id']; #订单ID
        $goods_id = $order['goods_id']; #盒子ID
        $prize_num = $order['prize_num']; #抽奖数量
        $order_type = $order['order_type']; #订单类型
        $prize_card_set = $order['prize_card_set'] ? json_decode($order['prize_card_set'], true) : ''; #抽卡机必出设置
        // dd($order);
        #排除必出等级卡条件
        $shang_where = [];
        // dd(11111);
        #必出卡等级
        $set_prize_shang = [];
        if ($prize_card_set && isset($prize_card_set['shang_id']) && isset($prize_card_set['shang_count'])) {

            // dd($prize_card_set['shang_count']);
            // foreach ($prize_card_set as $set_key => $set_value) {

            for ($seti = 1; $seti <= $prize_card_set['shang_count']; $seti++) {
                $set_prize_shang[] = $prize_card_set['shang_id'];
            }
            // }
            // dd($set_prize_shang);

            #排除必出等级卡条件
            $shang_where[] = ['id', 'not in', array_unique($set_prize_shang)];
            #减去必出数量
            $prize_num = $prize_num - count($set_prize_shang);
        }

        // dd($shang_where);
        #卡等级随机
        $shang = CardLevel::field('id,title')
            // ->where('goods_id', '=', $goods_id)
            //            ->where('pro', '>', 0)
            ->where($shang_where)
            ->select()->toArray();
        //  dd(1111)
        // dd($shang);
        if ($shang) {

            #卡等级随机
            $all_shang_id = [];
            foreach ($shang as $shang_value) {
                //                $real_shang_pro = $shang_value['pro'] * 100;
                //                for ($is = 1; $is <= $real_shang_pro; $is++) {
                $goods = GoodsList::where('shang_id', $shang_value['id'])->where('goods_id', '=', $goods_id)->find();
                if ($goods) {
                    $all_shang_id[] = $shang_value['id'];
                }

                //                }
            }
            // dd($all_shang_id);
            #中奖卡等级
            $prize_shang = [];
            for ($i = 0; $i < $prize_num; $i++) {
                #随机打乱
                shuffle($all_shang_id);
                shuffle($all_shang_id);
                $prize_shang[] = $all_shang_id[0];
            }
            // dd($prize_shang);
            $prize_shang = array_merge($prize_shang, $set_prize_shang);
            shuffle($prize_shang);
            $save_prize_data = [];
            // dd($prize_shang);
            #根据卡等级中奖奖品
            foreach ($prize_shang as $prize_shang_id) {
                #查找奖品
                $goodslist = GoodsList::field('id,shang_id,real_pro,special_stock')
                    ->where('goods_id', '=', $goods_id)
                    ->where('shang_id', '=', $prize_shang_id)
                    ->where('num', '=', 0)
                    ->where('real_pro', '>', 0)
                    ->where('special_stock = -100 OR special_stock > 0')
                    ->select()->toArray();
                if (empty($goodslist)) {
                    $res[] = 0;
                    return $res;
                }
                // dd($goodslist);
                if ($goodslist) {
                    #组合中奖商品
                    $all_goods_id = [];
                    foreach ($goodslist as $value) {
                        $real_pro = $value['real_pro'] * 100;
                        for ($i = 1; $i <= $real_pro; $i++) {
                            $all_goods_id[] = $value['id'];
                        }
                    }
                    #随机打乱
                    shuffle($all_goods_id);
                    shuffle($all_goods_id);
                    $prize_id = $all_goods_id[0];
                    $prize_info = GoodsList::where(['id' => $prize_id])->find();
                    $save_prize_data[] = [
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                        'status' => 0, #0未操作 1选择兑换 2选择发货
                        'goods_id' => $goods_id,
                        'num' => 0,
                        'shang_id' => $prize_info['shang_id'],
                        'goodslist_id' => $prize_info['id'],
                        'goodslist_title' => $prize_info['title'],
                        'goodslist_imgurl' => $prize_info['imgurl'],
                        'goodslist_price' => $prize_info['price'],
                        'goodslist_money' => $prize_info['money'],
                        'goodslist_type' => $prize_info['goods_type'],
                        'goodslist_sale_time' => $prize_info['sale_time'],
                        'addtime' => time(),
                        'prize_code' => $prize_info['prize_code'],
                        'order_type' => $order_type,
                    ];
                    if ($prize_info['special_stock'] >= 1) {
                        #减少库存
                        $res[] = GoodsList::field('special_stock')
                            ->where(['id' => $prize_info['id']])
                            ->dec('special_stock')
                            ->update();
                    }
                } else {
                    $res[] = $prize_shang_id;
                }
            }
            #入库===
            $res[] = OrderList::insertAll($save_prize_data);
        } else {
            $res[] = 0;
        }
        return $res;
    }

    /**
     * 背包发货订单处理
     * @param int $user_id 用户id
     * @param int $order_id 订单id
     */
    public function reward_order_handle($user_id = 0, $order_id = 0)
    {
        $res = [];
        $send_info = OrderListSend::where(['user_id' => $user_id])
            ->where('user_id', '=', $user_id)
            ->where('id', '=', $order_id)
            ->where('status', '=', 0) #0待支付 1待发货 2待收货 3已完成
            ->find();
        if ($send_info) {
            #改变订单状态
            $res[] = OrderListSend::field('id,status,pay_time')
                ->where('id', '=', $order_id)
                ->update([
                    'status' => 1, #0待支付 1待发货 2待收货 3已完成
                    'pay_time' => time(), #支付时间
                ]);
            #改变赏品信息
            $res[] = OrderList::field('id,status,send_num,choice_time')
                ->where('user_id', '=', $user_id)
                ->where('status', '=', 0)
                ->where('goodslist_type', '=', 1)
                ->where('send_num', '=', $send_info['send_num'])
                ->update([
                    'status' => 2,
                    'choice_time' => time(),
                ]);
        } else {
            $res[] = 0;
        }
        return $res;
    }


    //秒杀商城订单回调


    /**
     *
     * 商城商品回调修改订单状态
     * $out_trade_no  商城订单号
     *
     */
    public function update_product_order($out_trade_no, $pay_type = 1)
    {
        Db::startTrans();
        $orderInfo = Db::name('product_order')->where('order_num', '=', $out_trade_no)->where('status', '=', 1)->find();

        $orderInfoList = ProductOrderList::where(['order_id' => $orderInfo['id']])->find();
        #这个订单存在状态
        $res = [];
        try {
            if (!empty($orderInfo) && !empty($orderInfoList) && $orderInfo['status'] == 1) {
                $user_id = $orderInfo['user_id'];
                $total_price = $orderInfo['total'];  //  实际支付价格
                // 记录微信支付 排行榜  
                if ($total_price > 0) {
                    $res[] = ProfitPay::insert([
                        'user_id' => $user_id,
                        'order_num' => $out_trade_no,
                        'change_money' => $total_price,
                        'content' => '商城商品购买',
                        'pay_type' => $pay_type, #1微信 2支付宝
                        'addtime' => time(),
                    ]);
                }
                /******************2024-11-30 号以后要隐藏不计算*******************************/
                # 实时营收
                $res[] = ProfitRank::insert([
                    'user_id' => $user_id,
                    'order_num' => $out_trade_no,
                    'change_money' => $orderInfo['total_price'], // 订单总金额
                    'content' => '商城商品购买',
                    'pay_type' => $pay_type, #1微信 2支付宝
                    'addtime' => time(),
                ]);
                /******************2024-11-30 号以后要隐藏不计算*******************************/
                //修改订单状态
                $res[] = Db::name('product_order')->where('id', $orderInfo['id'])->update(['status' => 2, 'pay_time' => time(), 'update_time' => time()]);
                $res[] = Db::name('product_order_list')->where('order_id', $orderInfo['id'])->update(['status' => 2]);

                //修改商品销量和库存
                $res[] = Db::name('product')->where('id', $orderInfoList['product_id'])->inc('sales', 1)->dec('stock', 1)->update();
                $res[] = Db::name('product_norms_value')->where('sku', $orderInfoList['sku'])->where('product_id', $orderInfoList['product_id'])->inc('sales', 1)->dec('stock', 1)->update();

                //扣余额
                if ($orderInfo['use_money'] > 0) {
                    $ret = User::changeMoney($user_id, -$orderInfo['use_money'], 3, '购买商城商品' . $orderInfoList['title']);
                    $res = array_merge($res, $ret);
                }
                //扣赏币
                if ($orderInfo['use_integral'] > 0) {
                    $ret = User::changeIntegral($user_id, -$orderInfo['use_integral'], 2, '购买商城商品' . $orderInfoList['title']);
                    $res = array_merge($res, $ret);
                }

                //分销奖励
                $order['price'] = $total_price;
                $order['user_id'] = $user_id;
                $return = User::distribution($order);
                if (is_array($return)) {
                    $res = array_merge($res, $return);
                } else {
                    $res[] = $return;
                }
            }
            //通知微信发货信息
            $this->wx_gf_fahuo($user_id, $out_trade_no);
            if (resCheck($res)) {
                Db::commit();
                return 1;
            } else {
                Db::rollback();
                return 2;
            }
        } catch (\Exception $e) {
            Db::rollback();
            return 2;
        }
    }

    /**
     * 更改集市订单状态
     * @param $market_order_id
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update_js_order($market_order_id)
    {
        $order = Db::name('market_order')->where('id', $market_order_id)->find();;
        Db::startTrans();
        try {
            $res[] = Db::name('market_order')->where('id', $market_order_id)->update(['status' => 2, 'pay_time' => time(), 'update_time' => time()]);

            $res[] = Db::name('market')->where('id', $order['market_id'])->dec('stock', 1)->update(['status' => 1, 'update_time' => time()]);

            #扣市集余额
            if ($order['money'] > 0) {
                $res[] = User::changeMoney2($order['user_id'], -$order['money'], 3, '市集消费');
            }
            //给出售者钱
            if ($order['total'] > 0) {
                $market = Db::name('market')->field('user_id,price')->where('id', $order['market_id'])->find();;
                $res[] = User::changeMoney2($market['user_id'], $order['total'], 4, '市集售卖');
            }
            $order_list = Db::name('order_list')->whereIn('id', explode(',', $order['order_list_ids']))->select()->toArray();
            $data = [];
            foreach ($order_list as $k => $v) {
                unset($v['id']);
                $v['user_id'] = $order['user_id'];
                $v['order_id'] = $market_order_id;
                $v['status'] = 0;
                $v['addtime'] = time();
                $v['source'] = 2;
                $data[$k] = $v;
            }
            $res[] = Db::name('order_list')->insertAll($data);

            if (resCheck($res)) {
                Db::commit();
                return 1;
            } else {
                Db::rollback();
                return 2;
            }
        } catch (\Exception $e) {
            Db::rollback();
            return 2;
        }
    }

    public function order_notify7()
    {
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        //        wri($result['out_trade_no'], '秒杀商城回调--' . $result['out_trade_no']);
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                //                writelog($out_trade_no, "秒杀商城支付成功--");
                Db::startTrans();
                $res[] = $this->order_update($out_trade_no, 7);
                if (resCheck($res)) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            }
        }
        $html = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        die($html);
    }

    public static function order_update($order_num, $type)
    {
        $res = [];
        $order_info = Db::name('kk_order')
            ->where(['order_no' => $order_num])
            ->where(['status' => 0]) #0待付款 1待发货 2待收货 3确认收货
            ->find();
        if ($order_info) {
            #改变订单状态
            $res[] = Db::name('kk_order')->field('id,status,pay_time')
                ->where(['id' => $order_info['id']])
                ->update([
                    'status' => 1, #0待付款 1待发货 2待收货 3确认收货
                    'pay_time' => time(), #支付时间
                ]);
            if ($order_info['money'] > 0) {
                //                dd($order_info['user_id']);
                User::changeMoney($order_info['user_id'], '-' . $order_info['money'], 7);
            }
            if ($order_info['integral'] > 0) {
                User::changeIntegral($order_info['user_id'], '-' . $order_info['integral'], 4);
            }
            $goods_data = Db::name('kk_order_good')
                ->field('id,goods_id,goods_num,goods_spec_id')
                ->where(['order_id' => $order_info['id']])
                ->select()->toArray();
            foreach ($goods_data as $k => $v) {
                #加销量
                Db::name('kk_product')
                    ->field('id,sale_num')
                    ->where('id', $v['goods_id'])
                    ->inc('sale_num', $v['goods_num'])
                    ->update();
                #减库存
                Db::name('kk_product_spec')
                    ->field('id,stock')
                    ->where('id', $v['goods_spec_id'])
                    ->dec('stock', $v['goods_num'])
                    ->update();
            }
        } else {
            $res[] = 0;
        }
        return $res;
    }

    /**
     * 抽奖券======================================================
     * @param int $user_id 会员id
     * @param int $order_id 订单ID
     * @param int $box_id 盲盒id
     */
    public function draw_drawprize_notice($user_id = 0, $order_id = 0, $goods_id = 0, $pay_type = 1)
    {
        $res = [];

        $order = Order::where(['id' => $order_id])
            ->where(['user_id' => $user_id])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->where(['status' => 0])
            ->where(['order_type' => 7])
            ->find();
        if ($order) {
            #改变状态
            $res[] = Order::field('status,pay_time')
                ->where(['id' => $order['id']])
                ->update([
                    'status' => 1,
                    'pay_time' => time(),
                ]);
            #实时记录    
            $res[] = ProfitRank::insert([
                'user_id' => $user_id,
                'order_num' => $order['order_num'],
                'change_money' => $order['order_total'],
                'content' => '购买抽赏' . $order['goods_title'],
                'pay_type' => $pay_type, #1微信 2支付宝
                'addtime' => time(),
            ]);
            #扣抽奖券
            if ($order['use_draw'] > 0) {
                $res[] = User::changeDraw($order['user_id'], -$order['use_draw'], 3, '抽奖券消费' . $order['goods_title']);
            }
            #开奖==================================================
            $res[] = $this->draw_drawprize($order);
            #开奖==================================================
        } else {
            $res[] = 0;
        }

        return $res;
    }

    /**
     * 道具卡开奖逻辑
     * @param $order 订单信息
     */
    protected function draw_drawprize($order = [])
    {
        $user_id = $order['user_id']; #用户ID
        $order_id = $order['id']; #订单ID
        $goods_id = $order['goods_id']; #盒子ID
        $prize_num = $order['prize_num']; #抽奖数量
        $order_type = $order['order_type']; #订单类型

        #查找奖品
        $goodslist = GoodsList::field('id,shang_id,real_pro')
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', 0)
            ->where('real_pro', '>', 0)
            ->select()->toArray();
        if ($goodslist) {
            #组合中奖商品
            $all_goods_id = [];
            foreach ($goodslist as $value) {
                $real_pro = $value['real_pro'] * 10000;
                for ($i = 1; $i <= $real_pro; $i++) {
                    $all_goods_id[] = $value['id'];
                }
            }
            for ($i = 0; $i < $prize_num; $i++) {
                #随机打乱
                shuffle($all_goods_id);
                shuffle($all_goods_id);
                $prize_id = $all_goods_id[0];
                $prize_info = GoodsList::where(['id' => $prize_id])->find();
                #编号
                $luck_no = OrderList::field('id')
                    ->where('goods_id', '=', $goods_id)
                    ->where('num', '=', 0)
                    ->where('order_type', '=', $order_type)
                    ->order('id desc')
                    ->value('luck_no');
                $luck_no++;
                #新增记录
                $save_prize_info = [
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'status' => 0, #0未操作 1选择兑换 2选择发货
                    'goods_id' => $goods_id,
                    'num' => 0,
                    'shang_id' => $prize_info['shang_id'],
                    'goodslist_id' => $prize_info['id'],
                    'goodslist_title' => $prize_info['title'],
                    'goodslist_imgurl' => $prize_info['imgurl'],
                    'goodslist_price' => $prize_info['price'],
                    'goodslist_money' => $prize_info['money'],
                    'goodslist_type' => $prize_info['goods_type'],
                    'goodslist_sale_time' => $prize_info['sale_time'],
                    'addtime' => time(),
                    'prize_code' => $prize_info['prize_code'],
                    'order_type' => $order_type,
                    'luck_no' => $luck_no,
                ];
                #入库===
                $res[] = OrderList::insert($save_prize_info);
            }
        } else {
            $res[] = 0;
        }
        return $res;
    }

    /**
     * 道具卡======================================================
     * @param int $user_id 会员id
     * @param int $order_id 订单ID
     * @param int $box_id 盲盒id
     */
    public function item_card_notice($user_id = 0, $order_id = 0, $goods_id = 0)
    {
        $res = [];

        $order = Order::where(['id' => $order_id])
            ->where(['user_id' => $user_id])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->where(['status' => 0])
            ->find();
        if ($order) {
            #改变状态
            $res[] = Order::field('status,pay_time')
                ->where(['id' => $order['id']])
                ->update([
                    'status' => 1,
                    'pay_time' => time(),
                ]);
            #扣道具卡
            if ($order['use_item_card'] > 0) {
                $res[] = Db::name('user_item_card')->where(['user_id' => $user_id, 'status' => 1])->order('id asc')->limit($order['use_item_card'])->update(['status' => 2, 'order_id' => $order_id, 'updatetime' => time()]);
            }
            #开奖==================================================
            $res[] = $this->draw_drawprize($order);
            #开奖==================================================
        } else {
            $res[] = 0;
        }

        return $res;
    }

    //  通知微信发货信息
    public function wx_gf_fahuo($user_id, $order_num)
    {
        //微信官方发货
        $wxServer = new \app\common\server\Wx($this->app);

        $access_token = $wxServer->get_access_token();
        $open_id = Db::name('user')->where('id', $user_id)->value('openid');
        $wxServer->post_order($open_id, $access_token, $order_num);
    }
}
